package me.itsoo.artemis.framework.repository.interceptor;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import me.itsoo.artemis.framework.core.util.AnnotationUtils;
import me.itsoo.artemis.framework.core.util.Assert;
import me.itsoo.artemis.framework.core.util.ReflectUtils;
import me.itsoo.artemis.framework.core.util.StringUtils;
import me.itsoo.artemis.framework.ioc.lang.Matches;

import java.util.Objects;
import java.util.regex.Pattern;

/**
 * 规则匹配器
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/23
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MatchPatterns {

    /**
     * 先实现正则匹配，Ant匹配器较复杂，暂未实现
     *
     * @param sqlInterceptor SqlInterceptor
     * @param invocation     Invocation
     * @return boolean
     */
    public static boolean match(SqlInterceptor sqlInterceptor, Invocation invocation) {
        Assert.notNull(sqlInterceptor, "'sqlInterceptor' cannot be null");

        if (sqlInterceptor instanceof Matched) {
            final Matched matched = (Matched) sqlInterceptor;
            return matched.match(invocation.getMethod());
        }

        final Matches ann = AnnotationUtils.findAnnotation(sqlInterceptor.getClass(), Matches.class);
        if (Objects.isNull(ann) || StringUtils.isBlank(ann.value())) {
            return false;
        }

        final Pattern pattern = Pattern.compile(ann.value());
        final String methodName = ReflectUtils.getMethodNameNonNull(invocation.getMethod());
        return pattern.matcher(methodName).matches();
    }
}
